package com.richapp.launcher.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.box.udp.NetUDPBroadcastServer;
import com.richapp.net.udp.broadcast.server.UDPBroadCastMessageListener;

public class UdpService extends Service implements UDPBroadCastMessageListener {

    private NetUDPBroadcastServer netUDPBroadcastServer = null;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        netUDPBroadcastServer = NetUDPBroadcastServer.getInstance();
        netUDPBroadcastServer.setContext(this);
        netUDPBroadcastServer.setBoroacastMessageListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                netUDPBroadcastServer.start();
            }
        }).start();
        //保持服务
        Notification notification = new Notification();
        startForeground(4, notification);
        //Toast.makeText(this, "组播服务启动", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        netUDPBroadcastServer.stop();
    }

    /**
     * UDP 组播消息接收处理
     */
    @Override
    public void onUdpMessage(String fromIp, int fromPort, String message) {
        if (message == null) {
            return;
        }
        try{
            JSONObject jobj = JSON.parseObject(message);
            if (jobj == null) {
                return;
            }
            int type = jobj.getIntValue("type");
            switch (type) {
                case 11: // 打开二维码
                    netUDPBroadcastServer.doOpenQRcode(fromIp, fromPort, jobj);
                    break;
                case 12: //关闭二维码
                    netUDPBroadcastServer.doCloseQRcode(fromIp, fromPort, jobj);
                    break;
                case 29: //手机UDP搜索指定主机IP地址
                    netUDPBroadcastServer.doSearchHost(fromIp, fromPort, jobj);
                    break;
                case 200: //主机-主机 相互寻找
                    BoxServer.getInstance().doAreYouThere(jobj);
                    break;
                default:
                    //do nothing
                    break;
            }
        }catch(Exception e){
            Log.v("error", "接收组播消息错误:" + e.getMessage());
        }
    }
}
